<template>
    <van-sticky>
        <van-nav-bar
            title="确认订单"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        > 
        </van-nav-bar>
    </van-sticky>

    <van-contact-card type="add" @click="ToAddress" v-if="JSON.stringify(addressDefault) === '{}'"  />
    <van-contact-card type="edit" :tel="addressDefault.mobile" :name="addressDefault.consignee" @click="ToAddress" v-else />

    <van-card
        v-for="item in CartList"
        :key="item.id"
        :num="item.nums"
        :price="item.total"
        :title="item.product.name"
    >
        <template #thumb>
            <van-image
                width="88"
                height="88"
                fit="cover"
                :src="item.product.thumb_cdn"
            />
        </template>

        <template #desc>
            <div>
                商品单价：{{ item.product.price }}
            </div>
        </template>
        <template #tags>
            <van-tag plain type="danger" v-if="!item.attrs">无商品规格</van-tag>
            <div v-else>
                <van-tag plain type="primary" v-for="attr in JSON.parse(item.attrs)">{{ attr.value }}</van-tag>
            </div>
        </template>
    </van-card>

    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true" />

    <van-popup v-model:show="PayShow" round position="bottom">
        <van-picker
            title="选择支付方式"
            :columns="PayList"
            @cancel="PayShow = false"
            @confirm="onPayConfirm"
        />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell
        :coupons="CouponList"
        :chosen-coupon="CouponActive"
        @click="CouponShow = true"
    />

    <!-- 优惠券列表 -->
    <van-popup
        v-model:show="CouponShow"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px;"
    >
        <van-coupon-list
            :coupons="CouponList"
            :chosen-coupon="CouponActive"
            :exchange-button-disabled="true"
            :show-exchange-bar="false"
            @change="onCouponChange"
        />
    </van-popup>
    <!--订单备注 -->
    <van-field 
            v-model="remark"
            rows="2"
            autosize
            label="订单备注"
            type="textarea"
            maxlength="120"
            placeholder="请输入订单备注"
            show-word-limit
        />

    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="onSubmit" />


</template>

<script setup>
import { computed } from 'vue';

const { proxy } = getCurrentInstance();

onBeforeMount(() => {

    getCartListData();
    
    getCouponData();

    // 获取当前用户选择的收货地址
    let address = proxy.$cookies.get('address');

    if(address)
    {
        addressDefault.value = {
            id:address.id,
            consignee:address.name,
            mobile:address.tel
        };
    }else{
        getAddressDefaultInfo();
    }
})

const addressDefault = ref({});

const CartList = ref([]);
const cartids = ref(proxy.$route.query.cartids ?? 0)
const business = ref(proxy.$business.value ?? {})
const PayShow = ref(false);
const PayList = ref([
    {text:'余额支付',value:'money'},
    {text:'支付宝支付',value:'zfb'},
    {text:'微信支付',value:'wx'}
])
const PayActive = ref(PayList.value[0]);

// 优惠券
const CouponShow = ref(false);
const CouponList = ref([]);// 优惠券数据
const CouponActive = ref(-1);// 选择优惠券索引

const remark = ref('');

const total = computed(() => {
    let total = 0;

    if(CartList.value.length > 0)
    {
        for(let item of CartList.value)
        {
            total += parseFloat(item.total)
        }
    }

    if(CouponActive.value !== -1)
    {
        let CouponRate = CouponList.value[CouponActive.value].rate;

        total = total * parseFloat(CouponRate);
    }
    
    return total * 100;
})

const onSubmit = async () => {
    let params = {
        busid:proxy.$business.value.id,
        addrid:addressDefault.value.id,
        cartids:cartids.value,
        pay:PayActive.value.value,
        remark:remark.value
    }

    if(CouponActive.value !== -1)
    {
        // 用户领取优惠券的id
        params.couponid = CouponList.value[CouponActive.value].id
    }

    let result = await proxy.$post({
        url:'/product/order/add',
        params
    })

    if(result.code === 1)
    {
        proxy.$successNotify({
            message:result.msg,
            onClose:() => {
                proxy.$router.push('/product/order/index');
            }
        });
    }else{
        proxy.$warnNotify(result.msg);
    }

}

onBeforeUnmount(() => {
    proxy.$cookies.remove('address');
})

const onPayConfirm = ({selectedOptions}) => {
    PayActive.value = selectedOptions[0];

    PayShow.value = false;
}

const onCouponChange = (index) => {
    CouponActive.value = index;

    CouponShow.value = false;

    if(index !== -1)
    {
        let Total = 0;

        CartList.value.map(item => Total += parseFloat(item.total))

        let rate = CouponList.value[index].rate;

        let price = parseFloat(Total * rate).toFixed(2);

        let CouponPrice = Total - parseFloat(price);

        CouponList.value[index].value = CouponPrice * 100;

    }
}

const getCouponData = async () => {
    let params = {
        busid:proxy.$business.value.id
    }

    let result = await proxy.$post({
        url:'/product/order/coupon',
        params
    })

    if(result.code === 1)
    {
        for(let item of result.data)
        {
            CouponList.value.push({
                id:item.id,
                name:item.coupon.title,
                condition:item.coupon.status_text,
                startAt:item.coupon.createtime,
                endAt:item.coupon.endtime,
                rate: item.coupon.rate,
                valueDesc: `${item.coupon.rate*100}`,
                unitDesc: '折',
            })
        }
    }
}

const getCartListData = async () => {
    let params = {
        busid:business.value.id,
        cartids:cartids.value
    }

    let result = await proxy.$post({
        url:'/product/order/cart',
        params
    })

    if(result.code === 1)
    {
        CartList.value = result.data;

        return false;
    }else{
        proxy.$warnNotify({
            message:result.msg,
            onClose:() => onBack
        })

        return false;
    }
}

const ToAddress = () => {
    proxy.$router.push({path:'/business/address/index',query:{action:'order'}})
}

const getAddressDefaultInfo = async () => {
    let params = {
        busid:proxy.$business.value.id
    }

    let result = await proxy.$post({
        url:'/product/order/address',
        params
    })

    if(result.code === 1)
    {
        addressDefault.value = result.data;

        return false;
    }
}

const onBack = () => proxy.$router.back();
</script>